from api.models import Disk, ChangeRecord


def disk_handler(host, info):  # 添加变更记录
    if not info['status']:
        print(info['error'])

        return

    disk_dict = info['data']
    db_disk_queryset = Disk.objects.filter(host=host)
    db_disk_dict = {row.slot: row for row in db_disk_queryset}

    db_disk_slot_set = set(db_disk_dict)
    disk_slot_set = set(disk_dict)

    create_slot_set = disk_slot_set - db_disk_slot_set
    rm_slot_set = db_disk_slot_set - disk_slot_set
    update_slot_set = db_disk_slot_set & disk_slot_set

    change_record_list = []

    for slot in create_slot_set:  # 新增
        Disk.objects.create(**disk_dict[slot], host=host)
        msg = '【新增硬盘】槽位：{slot}, 类型: {pd_type}, 容量: {capacity}, 型号: {model}'.format(**disk_dict[slot])
        change_record_list.append(msg)

    if rm_slot_set:
        Disk.objects.filter(host=host, slot__in=rm_slot_set).delete()  # 删除
        msg1 = '【删除硬盘】槽位: {}'.format(', '.join(rm_slot_set))
        change_record_list.append(msg1)

    # 更新
    for slot in update_slot_set:
        msg2 = []
        for k, v in disk_dict[slot].items():
            old_v = getattr(db_disk_dict[slot], k)
            if v == old_v:
                continue
            setattr(db_disk_dict[slot], k, v)
            tmp = '{}由{}更新为{}'.format(k, old_v, v)
            msg2.append(tmp)

        if msg2:
            db_disk_dict[slot].save()
            msg3 = '【更新硬盘】槽位: {}, 更新内容: {}'.format(slot, ', '.join(msg2))
            change_record_list.append(msg3)

    if change_record_list:
        ChangeRecord.objects.create(text='\n'.join(change_record_list), host=host)
